<?php

namespace app\api\controller;

use app\admin\model\CashcardCate;
use app\admin\model\CashcardUser;
use app\admin\model\ShopCate;
use app\admin\model\UserBase;
use think\facade\Db;
use think\facade\Route;

class Cashcard extends Api
{

    public function index()
    {
        return $this->fetch();
    }

    public function detail()
    {
        return $this->fetch();
    }

    public function send()
    {
        return $this->fetch();
    }

    public function sendDetail()
    {
        return $this->fetch('send_detail');
    }

    public function sendHistory()
    {
        return $this->fetch('send_history');
    }

    public function select()
    {
        return $this->fetch();
    }

    /**
     * @title 获取我拥有的卡券
     * @author FashionJune
     */
    public function myCard()
    {
        $map = [
            ['to_user', '=', $this->user['user_id']]
        ];
        (input('status', null)) && ($map[] = ['status', '=', input('status')]);

        $list = Db::view('cashcard_user', 'id,cate_id,create_time,used_time,expire_time,status')
            ->view('cashcard_cate', 'min_order_price,cashcard_price,tips,attention,title,card_type,related_cate', 'cashcard_user.cate_id=cashcard_cate.id')
            ->where($map)
            ->select()->each(function ($item) {
                $item['create_at'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['used_at'] = date('Y-m-d H:i:s', $item['used_time']);
                $item['expire_at'] = date('Y-m-d H:i:s', $item['expire_time']);
                if ($item['card_type'] == 2) {
                    $item['cate_name'] = ShopCate::where('id', $item['related_cate'])->cache()->value('title');
                } else {
                    $item['cate_name'] = '通用券';
                }
                return $item;
            });
        $list1 = $list2 = $list3 = [];
        $count1 = $count2 = $count3 = 0;
        foreach ($list as $value) {
            if ($value['status'] == -2 || $value['status'] == 1) {//统一标记已使用
                $count2++;
                $list2[] = $value;
            } elseif ($value['expire_time'] < time()) {//已过期，未标记则更新状态
                $count3++;
                $list3[] = $value;
                ($value['status'] == 0) && CashcardUser::where('id', $value['id'])->find()->save(['status' => -1]);
            } else {
                $count1++;
                $list1[] = $value;
            }
        }
        api_success([
            'list1' => $list1,
            'count1' => $count1,
            'list2' => $list2,
            'count2' => $count2,
            'list3' => $list3,
            'count3' => $count3,
            'banner' => sysconfig('site', 'site_cashcard_banner'),
        ]);
//        $count = count($list);
//        api_list_return($count, $list);
    }

    /**
     * @title 获取代金券详情
     * @author FashionJune
     */
    public function cardDetail()
    {
        $id = input('id');
        $card_info = CashcardUser::withJoin([
            'admin' => ['id', 'bind_user'],
            'user' => ['id', 'bind_admin'],
            'cate' => ['id', 'tips', 'attention', 'title', 'min_order_price', 'cashcard_price']
        ],'LEFT')->find($id)->toArray();
        (!$card_info) && api_error('卡券不存在');
        ($card_info['admin']['bind_user'] == $this->user['user_id']) || ($card_info['user']['id'] == $this->user['user_id']) || api_error('无权限访问');
        $card_info['tips'] = explode('|', $card_info['cate']['tips']);
        $card_info['attention'] = explode('|', $card_info['cate']['attention']);
//        dd($card_info);
        api_success($card_info);
    }

    /**
     * @title 发放列表
     * @author FashionJune
     */
    public function sendList()
    {
        $admin_id = UserBase::init()->getBindAdmin($this->user['user_id']);
        $map = [
            ['card_author', 'find in set', $admin_id]
        ];
        $cate_id = input('cate_id/d', -100);
        if ($cate_id === 0) {
            $map[] = ['card_type', '=', 1];
        } elseif ($cate_id > 0) {
            $map[] = ['related_cate', '=', $cate_id];
        }
        $list = CashcardCate::where($map)->with('cards')->select();
        $count1 = $count2 = 0;
        $list1 = $list2 = [];
        foreach ($list as $value) {
            //减去已发放的额度
            $map_send_history = [
                ['to_admin', '=', $admin_id],
                ['cate_id', '=', $value['id']]
            ];
            $send_num = CashcardUser::where($map_send_history)->count();
            $value->rest_num = min($value->num_person - $send_num, $value->rest_num);
            if ($value->rest_num > 0) {//待发放
                $count1++;
                $list1[] = $value;
            } else {//已发完
                $count2++;
                $list2[] = $value;
            }
        }
        api_success([
            'list1' => $list1,
            'count1' => $count1,
            'list2' => $list2,
            'count2' => $count2,
        ]);
//        api_list_return($count, $list);
    }

    /**
     * @title 获取发放历史记录
     * @author FashionJune
     */
    public function getSendHistoryList()
    {
        $cate_id = input('cate_id', null);
        (!$cate_id) && (api_error('缺少卡券组id参数'));
        $admin_id = UserBase::init()->getBindAdmin($this->user['user_id']);
        $map = [
            ['cate_id', '=', $cate_id],
            ['to_admin', '=', $admin_id],
            ['to_user', '>', 0],
        ];
        $list = CashcardUser::where($map)->with(['user' => function($query){
            $query->field(['id', 'nickname']);
        }])->select();
        api_list_return($list);
    }


    /**
     * @title 获取二维码
     * @author FashionJune
     */
    public function getCardCode()
    {
        $cate_id = input('cate_id', null);
        (!$cate_id) && (api_error('缺少卡券组id参数'));
        //检测是否有权限
        $admin_id = UserBase::init()->getBindAdmin($this->user['user_id']);
        $map = [
            ['id', '=', $cate_id],
            ['card_author', 'find in set', $admin_id],
        ];
        $cate_info = CashcardCate::where($map)->find();
        (!$cate_info) && api_error('权限不足');
        $map_card = [
            ['status', '=', 0],
            ['to_user', '=', 0],
            ['to_admin', '=', 0],
            ['cate_id', '=', $cate_id]
        ];
        $card_info = CashcardUser::where($map_card)->find();
        if (!$card_info) {
            api_error('已无可用卡券');
        }
        $card_info['url'] = url('/api/cashcard-accept', [
            'code' => $card_info['code'],
            'admin_id' => $admin_id,
        ])->domain(true)->build();
        //减去已发放的额度
        $map_send_history = [
            ['to_admin', '=', $admin_id],
            ['cate_id', '=', $cate_info['id']]
        ];
        $send_num = CashcardUser::where($map_send_history)->count();
        $card_info['rest_num'] = min($cate_info['num_person'] - $send_num, $cate_info['rest_num']);
        $card_info['attention'] = str2arr($card_info['attention'], '|');
        api_success($card_info);
    }

    /**
     * @title 获取卡类型
     * @author FashionJune
     */
    public function getCardType()
    {
        $type_list = [
            ['id' => -100, 'title' => '所有分类'],
            ['id' => 0, 'title' => '通用券']
        ];
        $list = ShopCate::where('status', 1)->column('title', 'id') ?? [];
        $type_list = array_merge($type_list, arr2id_title($list));
        api_success($type_list);
    }

    /**
     * @title 领取代金券
     * @author FashionJune
     */
    public function acceptCashcard()
    {
        $code = input('code');
        $admin_id = input('admin_id', null) ?? $this->error('此卡已被领取', [], '/api/index.html');
        $card_info = CashcardUser::where('code', $code)->find();
        ((!$card_info) || $card_info['to_user'] > 0) && $this->error('此卡已被领取，请管理员刷新重试', [], '/api/index.html');
        $re = false;
        try {
            $update_data = [
                'to_admin' => $admin_id,
                'to_user' => $this->user['user_id'],
                'send_time' => time(),
            ];
            $re = $card_info->save($update_data);
        } catch (\Exception $e) {
            $this->error('领取失败，请重试', [], '/api/index.html');
//            api_error('领取失败，请重试');
        }
        $re && $this->success('扫码领取成功', [], '/api/cashcard-detail.html?id=' . $card_info['id']) || $this->error('领取失败，请重试', [], '/api/index.html');
    }

}
